<?php
namespace plugin\ky_shouyin\app\controller\front;

use support\Request;
use support\Db;
use plugin\ky_shouyin\app\controller\BaseController;

class OrderController extends BaseController
{
    /**
     * 订单列表页面
     */
    public function list()
    {
        return $this->view('front/order/list');
    }
    
    /**
     * 获取订单列表数据
     */
    public function getList(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $startDate = $request->get('start_date');
        $endDate = $request->get('end_date');
        $keyword = $request->get('keyword', '');
        $status = $request->get('status');
        
        $query = Db::table('ky_order')
            ->leftJoin('ky_member', 'ky_order.user_id', '=', 'ky_member.id')
            ->where('ky_order.store_id', session('user.store_id'));
            
        // 日期筛选
        if ($startDate && $endDate) {
            $query->whereBetween('ky_order.created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);
        }
        
        // 状态筛选
        if ($status !== '' && $status !== null) {
            $query->where('ky_order.status', $status);
        }
        
        // 关键词搜索
        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('ky_order.order_no', 'like', "%{$keyword}%")
                    ->orWhere('ky_member.name', 'like', "%{$keyword}%")
                    ->orWhere('ky_member.phone', 'like', "%{$keyword}%");
            });
        }
        
        $total = $query->count();
        
        $orders = $query->select([
                'ky_order.*',
                'ky_member.name as member_name',
                'ky_member.phone as member_phone'
            ])
            ->orderBy('ky_order.created_at', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();
            
        // 获取订单商品信息
        foreach ($orders as &$order) {
            $order->goods = Db::table('ky_order_goods')
                ->where('order_id', $order->id)
                ->get();
        }
        
        return json([
            'code' => 0,
            'msg' => 'ok',
            'count' => $total,
            'data' => $orders
        ]);
    }

    /**
     * 订单退款
     */
    public function refund(Request $request)
    {
        try {
            $id = $request->post('id');
            
            // 开启事务
            Db::beginTransaction();
            
            // 获取订单信息
            $order = Db::table('ky_order')
                ->where('id', $id)
                ->where('status', 1)  // 已支付状态
                ->where('is_refunded', 0)  // 未退款
                ->first();
                
            if (!$order) {
                throw new \Exception('订单不存在或已退款');
            }
            
            // 如果是会员余额支付，退还余额
            if ($order->pay_type == 3 && $order->user_id) {
                // 获取会员信息和当前余额
                $member = Db::table('ky_member')
                    ->where('id', $order->user_id)
                    ->first();
                    
                if (!$member) {
                    throw new \Exception('会员信息不存在');
                }
                
                // 更新会员余额
                $result = Db::table('ky_member')
                    ->where('id', $order->user_id)
                    ->increment('balance', $order->paid_amount);
                    
                if (!$result) {
                    throw new \Exception('退还会员余额失败');
                }
                
                // 记录余额变动日志
                Db::table('ky_member_balance_log')->insert([
                    'member_id' => $order->user_id,
                    'type' => 2,  // 退款
                    'amount' => $order->paid_amount,
                    'before_balance' => $member->balance,
                    'after_balance' => $member->balance + $order->paid_amount,
                    'order_id' => $order->id,
                    'remark' => '订单退款',
                    'store_id' => $order->store_id,
                    'operator_id' => session('staff.id'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            // 更新订单状态
            $result = Db::table('ky_order')
                ->where('id', $id)
                ->update([
                    'status' => 2,  // 已退款状态
                    'is_refunded' => 1,
                    'refund_start_time' => date('Y-m-d H:i:s'),
                    'refund_success_time' => date('Y-m-d H:i:s'),
                    'remark' => ($order->remark ? $order->remark . '；' : '') . '前台操作退款',
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
                
            if (!$result) {
                throw new \Exception('更新订单状态失败');
            }
            
            // 提交事务
            Db::commit();
            
            return json(['code' => 0, 'msg' => '退款成功']);
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollBack();
            return json(['code' => 1, 'msg' => '退款失败：' . $e->getMessage()]);
        }
    }

    /**
     * 订单详情
     */
    public function detail(Request $request)
    {
        $id = $request->get('id');
        
        // 获取订单信息
        $order = Db::table('ky_order')
            ->leftJoin('ky_member', 'ky_order.user_id', '=', 'ky_member.id')
            ->leftJoin('ky_staff', 'ky_order.staff_id', '=', 'ky_staff.id')
            ->leftJoin('ky_store', 'ky_order.store_id', '=', 'ky_store.id')
            ->where('ky_order.id', $id)
            ->select([
                'ky_order.*',
                'ky_member.name as member_name',
                'ky_member.phone as member_phone',
                'ky_staff.name as staff_name',
                'ky_store.name as store_name'
            ])
            ->first();
        
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }
        
        // 获取订单商品
        $order->goods = Db::table('ky_order_goods')
            ->where('order_id', $id)
            ->get();
        
        if ($request->isAjax()) {
            return json(['code' => 0, 'msg' => 'ok', 'data' => $order]);
        }
        
        return $this->view('front/order/detail', ['order' => $order]);
    }
}